package tools;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import lombok.Data;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

/**
 * @author malguy-wang sir
 * @create ---
 */
@Data
public class druid {
    private QueryRunner qr = new QueryRunner();

    public Connection druid() throws Exception {
        Properties pro = new Properties();
        //引入配置文件，druidTest.class.getClassLoader()根据当前类是哪个类来写
        pro.load(druid.class.getClassLoader().getResourceAsStream("druid.properties"));
        //获取数据源
        DataSource ds = DruidDataSourceFactory.createDataSource(pro);
        //从数据源（连接池）里获取连接
        Connection conn = ds.getConnection();
        return conn;
    }

    public void close(Connection conn, PreparedStatement ps) {
        try {
            if (conn != null) conn.close();
            if (ps != null) ps.close();
        } catch (Exception e) {
        }
    }

    //通用插入方法
    private void insert(String sql, Object... args) {
//        String sql = "insert into customers(name,email,birth,photo) values(?,?,?,?)";
        try {
            int count = qr.update(druid(), sql, args[0], args[1], args[2], null);
            System.out.println("添加了" + count + "条记录");
        } catch (Exception e) {
        } finally {
            try {
                close(druid(), null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

//    }
//    public static void del(Scanner scanner){
//        System.out.println("请输入要删除的id");
//        int id = scanner.nextInt();
//        try {
//            int s = delete(id);
//            if(s == 0){
//                System.out.println("你输入的id不存在");
//            }
//        } catch (Exception e) {
//        }
//    }
//    //根据id删除
//    private static int delete(int id)throws Exception{
//        QueryRunner runner = new QueryRunner();
//        Connection conn = druid();
//        String sql = "delete from customers where id = ?" ;
//        int count = runner.update(conn,sql,id);
//        System.out.println("删除了" + count + "条记录");
//        close(conn,null);
//        return count;
//    }

//    private static void update(int id,Object...args) throws Exception{
//        QueryRunner qr = new QueryRunner();
//        Connection conn = druid();
//        String sql = "update customers set name=?, email=?, birth=?  where id = ?";
//        int count = qr.update(conn,sql,args[0],args[1],args[2],id);
//        System.out.println("添加了" + count + "条记录");
//        close(conn, null);
//    }

//    }

